package com.dht.xiao.jianye.dayin.ui;



import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.DocumentsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.dht.xiao.jianye.R;
import com.dht.xiao.jianye.base.App;
import com.dht.xiao.jianye.dayin.ErrorOrMsg;
import com.dht.xiao.jianye.dayin.MyApplication;
import com.dht.xiao.jianye.dayin.PrintContent;
import com.dht.xiao.jianye.dayin.PrinterManager;
import com.dht.xiao.jianye.dayin.util.ToastUtil;
import com.dht.xiao.jianye.dayin.Event;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.concurrent.ExecutionException;


public class PrinterMainActivity extends Activity implements OnClickListener {
    private MyApplication myapplication;
    private Button buttonClose, btnPrnSetting, btnPrintTxt, btnPrintPic, btnFeed, btnBack, btnPrintFile,
            btnPrintExcel, btnStatus, btnPrintHtml, btnPrintJSON;
    private static ProgressDialog m_pDialog;
    private TextView tv_version; // 软件版本
    private PrinterManager printerManager = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // 渐变色 WHITE
        GradientDrawable grad = new GradientDrawable(Orientation.TOP_BOTTOM,
                new int[]{Color.rgb(251, 247, 222), Color.rgb(214, 74, 185)});
        getWindow().setBackgroundDrawable(grad);

        requestWindowFeature(Window.FEATURE_NO_TITLE);//无标题
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_print_main);
        // 初始化view
        initView();
    }

    private void initView() {
        // 创建通讯对话框
        m_pDialog = new ProgressDialog(this);
        m_pDialog.setMessage(getResources().getString(R.string.printing));
        m_pDialog.setIndeterminate(false);
        m_pDialog.setCancelable(true); // 设置对话框不可取消
        // 获取控件对象
        btnPrnSetting = (Button) findViewById(R.id.btnPrnSetting);// 打印机设置按钮
        buttonClose = (Button) findViewById(R.id.buttonClose);// 关闭按钮
        btnPrintTxt = (Button) findViewById(R.id.btnPrintTxt);// 文本打印按钮
        btnPrintPic = (Button) findViewById(R.id.btnPrintPic);// 图片打印按钮
        btnPrintExcel = (Button) findViewById(R.id.btnPrintExcel);// 表格打印按钮
        btnFeed = (Button) findViewById(R.id.btnFeedPaper);// 走纸按钮
        btnBack = (Button) findViewById(R.id.btnBackPaper);// 退纸按钮
        btnPrintFile = (Button) findViewById(R.id.btnPrintfile);// 发送打印机指令文件按钮
        tv_version = (TextView) findViewById(R.id.tv_version);// 软件版本
        btnStatus = (Button) findViewById(R.id.btnGetStatus); //获取USB打印机状态
        btnPrintHtml = (Button) findViewById(R.id.btnPrintHtml);//网页打印
        btnPrintJSON = (Button) findViewById(R.id.btnPrintJSON);//JSON打印

        // 设置版本号信息
        try {
            tv_version.setText(getResources().getString(R.string.printer_title)
                    + getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName);
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        // 设置点击事件
        buttonClose.setOnClickListener(this);
        btnPrnSetting.setOnClickListener(this);
        btnFeed.setOnClickListener(this);
        btnBack.setOnClickListener(this);
        btnPrintTxt.setOnClickListener(this);
        btnPrintPic.setOnClickListener(this);
        btnPrintFile.setOnClickListener(this);
        btnPrintExcel.setOnClickListener(this);
        btnStatus.setOnClickListener(this);
        btnPrintHtml.setOnClickListener(this);
        btnPrintJSON.setOnClickListener(this);
        findViewById(R.id.btnGetPrintMode).setOnClickListener(this);

        myapplication = (MyApplication) getApplication();
        printerManager = myapplication.getPrinterManager();

        // 注册EventBus
        EventBus.getDefault().register(this);
    }

    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
            case R.id.btnPrnSetting: // 打印机设置
                Intent intent = new Intent(PrinterMainActivity.this, PrintSettingActivity.class);
                startActivity(intent);// 跳转到设置界面
                break;
            case R.id.btnGetPrintMode:
                if (printerManager == null)
                    return;
                String pm = printerManager.getPrinterModel();
                ToastUtil.show(PrinterMainActivity.this, pm);
                break;

            case R.id.buttonClose: // 关闭
                if (printerManager != null && printerManager.isConnected()) {
                    printerManager.close();
                }
                finish();
                System.exit(0);// 正常退出App
                break;
            case R.id.btnPrintTxt: // 文本打印
                printerManager.sendData(PrintContent.getTextByteData(this), this);
                break;
            case R.id.btnPrintPic: // 图片打印
                printerManager.sendData(PrintContent.getPicByteData(this), this);
                break;
            case R.id.btnPrintExcel: // 表格打印
                printerManager.sendData(PrintContent.getFormByteData(this), this);
                break;
            case R.id.btnFeedPaper: // 走纸
                printerManager.sendData(PrintContent.getFeedByteData(), this);
                break;
            case R.id.btnBackPaper: // 退纸
                printerManager.sendData(PrintContent.getBackByteData(), this);
                break;
            case R.id.btnPrintfile: // 发送打印机指令文件
//			try {
//				Intent intent2 = new Intent();
//				intent2.setAction(Intent.ACTION_GET_CONTENT);
//				Uri startDir = Uri.fromFile(new File("/sdcard"));
//				intent2.setDataAndType(startDir, "vnd.android.cursor.dir/lysesoft.andexplorer.file");
//				startActivityForResult(intent2, ErrorOrMsg.PICK_REQUEST_TEXT);
//			} catch (Exception e) {
//				ToastUtil.show(PrinterMainActivity.this, "请安装文件浏览器!");
//			}
                Intent chooseIntent = new Intent(Intent.ACTION_GET_CONTENT);
                chooseIntent.setType("*/*");
                chooseIntent.addCategory(Intent.CATEGORY_OPENABLE);
                startActivityForResult(Intent.createChooser(chooseIntent, "用于选择prn文件"), 0);
//			printerManager.sendData(PrintContent.getPrintData(this,"t10_c1"),this);
                break;
            case R.id.btnGetStatus: //查询打印机状态
                getUsbPrinterStatus();
                break;
            case R.id.btnPrintHtml:
                View htmlView = LayoutInflater.from(this).inflate(R.layout.dialog_print_html, null);
                View template1 = htmlView.findViewById(R.id.ll_template1);
                View template2 = htmlView.findViewById(R.id.ll_template2);
                View template3 = htmlView.findViewById(R.id.ll_template3);
                final AlertDialog htmlDialog = new AlertDialog.Builder(this)
                        .setView(htmlView)
                        .create();
                template1.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        htmlDialog.dismiss();
                        try {
                            printerManager.sendData(PrintContent.getHtmlPrintData(PrinterMainActivity.this, "html1.html"), PrinterMainActivity.this);
                        } catch (ExecutionException | InterruptedException e) {
                            ToastUtil.show(PrinterMainActivity.this, e.getMessage());
                            e.printStackTrace();
                        }
                    }
                });
                template2.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        htmlDialog.dismiss();
                        try {
                            printerManager.sendData(PrintContent.getHtmlPrintData(PrinterMainActivity.this, "html2.html"), PrinterMainActivity.this);
                        } catch (ExecutionException | InterruptedException e) {
                            ToastUtil.show(PrinterMainActivity.this, e.getMessage());
                            e.printStackTrace();
                        }
                    }
                });
                template3.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        htmlDialog.dismiss();
                        try {
                            printerManager.sendData(PrintContent.getHtmlPrintData(PrinterMainActivity.this, "html3.html"), PrinterMainActivity.this);
                        } catch (ExecutionException | InterruptedException e) {
                            ToastUtil.show(PrinterMainActivity.this, e.getMessage());
                            e.printStackTrace();
                        }
                    }
                });
                htmlDialog.show();
                break;
            case R.id.btnPrintJSON:
                View jsonView = LayoutInflater.from(this).inflate(R.layout.dialog_print_json, null);
                template1 = jsonView.findViewById(R.id.ll_template1);
                template2 = jsonView.findViewById(R.id.ll_template2);
                template3 = jsonView.findViewById(R.id.ll_template3);
                final AlertDialog jsonDialog = new AlertDialog.Builder(this)
                        .setView(jsonView)
                        .create();
                template1.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        jsonDialog.dismiss();
                        try {
                            printerManager.sendData(PrintContent.getJSONPrintData(PrinterMainActivity.this, "json1.json"), PrinterMainActivity.this);
                        } catch (ExecutionException | InterruptedException e) {
                            ToastUtil.show(PrinterMainActivity.this, e.getMessage());
                            e.printStackTrace();
                        }
                    }
                });
                template2.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        jsonDialog.dismiss();
                        try {
                            printerManager.sendData(PrintContent.getJSONPrintData(PrinterMainActivity.this, "json2.json"), PrinterMainActivity.this);
                        } catch (ExecutionException | InterruptedException e) {
                            ToastUtil.show(PrinterMainActivity.this, e.getMessage());
                            e.printStackTrace();
                        }
                    }
                });
                template3.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        jsonDialog.dismiss();
                        try {
                            printerManager.sendData(PrintContent.getJSONPrintData(PrinterMainActivity.this, "json3.json"), PrinterMainActivity.this);
                        } catch (ExecutionException | InterruptedException e) {
                            ToastUtil.show(PrinterMainActivity.this, e.getMessage());
                            e.printStackTrace();
                        }
                    }
                });
                jsonDialog.show();
                break;
        }

    }

    private void getUsbPrinterStatus() {
        byte[] buffer;
        buffer = printerManager.getUsbPrinterStatus(1000, this);
        if (buffer != null) {
            ToastUtil.show(PrinterMainActivity.this, getString(R.string.status) + buffer[0]);
        } else {
            ToastUtil.show(PrinterMainActivity.this, getString(R.string.status_error));
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 0:
                    String filePath = getFilePath(this, data.getData());
                    if (filePath == null) {
                        ToastUtil.show(this, getString(R.string.file_open_failure));
                        return;
                    }
                    System.out.println(filePath);
                    int number = 0;
                    byte[] buffer = new byte[0];
                    try {
                        DataInputStream dis = new DataInputStream(new FileInputStream(filePath));
                        int length = dis.available();
                        buffer = new byte[length];
                        number = dis.read(buffer);
                        dis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (number > 0) {
                        printerManager.sendData(buffer, this);
                    } else {
                        ToastUtil.show(this, R.string.file_read_failure);
                        return;
                    }
                    break;
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    public String getFilePath(Context context, Uri uri) {
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            System.out.println(uri);
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] projection = {"_data"};
            try {
                Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
                int column_index = cursor.getColumnIndexOrThrow("_data");
                if (cursor.moveToFirst()) {
                    return cursor.getString(column_index);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }

    public boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }
    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    // 接收发送事件信息
    public void onEventMainThread(Event event) {
        switch (event.msg) {
            case ErrorOrMsg.SEND_SUCCESSED:
                m_pDialog.dismiss();
                Log.d("SEND_SUCCESS", "-------------------------发送成功");
                ToastUtil.show(PrinterMainActivity.this, getResources().getString(R.string.send_success));
                if (printerManager.isConnected()) {
                    new Thread() {
                        public void run() {
                            printerManager.close();//打完关闭连接
                        }
                    }.start();
                    Log.d("发送成功", "---------------- 关闭连接");
                }
                break;
            case ErrorOrMsg.SEND_FAILED:
                m_pDialog.dismiss();
//                ToastUtil.show(PrinterMainActivity.this,getString(R.string.send_failed));
                Log.d("SEND_FAILED", "-------------------------发送失败");
//			if (printerManager.isConnected()) {
//				new Thread() {
//					public void run() {
//						printerManager.close();//打完关闭连接
//					}
//				}.start();
//				Log.d("发送失败", "---------------- 关闭连接");
//			}
                break;
            case ErrorOrMsg.CONFIG_NULL:
                m_pDialog.dismiss();
                Log.d("tag", "-------------------------配置为空");
                ToastUtil.show(PrinterMainActivity.this, R.string.no_choose);
                break;
            case ErrorOrMsg.DATA_EMPTY:
                m_pDialog.dismiss();
                ToastUtil.show(PrinterMainActivity.this, getString(R.string.data_empty));
                break;
            case ErrorOrMsg.PRINTERING:
                m_pDialog.show();
                break;
            case ErrorOrMsg.CONNECT_FAILED:
                m_pDialog.dismiss();
                ToastUtil.show(PrinterMainActivity.this, R.string.connect_faile);// 连接失败
                break;
            case ErrorOrMsg.CONNECTING:
                m_pDialog.dismiss();
                ToastUtil.show(PrinterMainActivity.this, getString(R.string.connecting));
                break;
            case ErrorOrMsg.PRINTERING_WAIT:
                ToastUtil.show(PrinterMainActivity.this, R.string.printing);// 打印中,请稍后
                break;

            case ErrorOrMsg.TASK_CANCEL_SUCCESS:
                ToastUtil.show(PrinterMainActivity.this, getString(R.string.task_cancel_success));
                break;
            case ErrorOrMsg.TASK_CANCEL_FAILED:
                ToastUtil.show(PrinterMainActivity.this, getString(R.string.task_cancel_failed));
                break;
        }
    }

//	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
//		if (requestCode == ErrorOrMsg.PICK_REQUEST_TEXT) {
//			if (resultCode == RESULT_OK) {
//				try {
//					Uri uri = intent.getData();
//					if (uri != null) {
//						String path = uri.toString();
//						path = path.substring(path.indexOf("/storage"), path.length());
//						// 打印prn文件
//						printerManager.sendData(PrintContent.getPrnByteData(path));
//					}else{
//						ToastUtil.show(PrinterMainActivity.this, "文件路径为空！");
//					}
//				} catch (Exception e) {
//					return;
//				}
//			}
//		}
//	}

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);//反注册EventBus
        super.onDestroy();
    }

    //----- 软件退出 --------------------------------
    int pressBackNum = 0;

    @Override
    public void onBackPressed() {
        pressBackNum++;
        if (1 == pressBackNum) {
            Toast.makeText(PrinterMainActivity.this, getString(R.string.press_exit), Toast.LENGTH_SHORT).show();
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    // 两秒后归零
                    pressBackNum = 0;
                }
            }, 2000);
        } else if (2 == pressBackNum) {
            super.onBackPressed();
            if (printerManager != null && printerManager.isConnected()) {
                printerManager.close();
            }
            this.finish();
        }
    }
}
